<?php
namespace common\models\behaviors;
use yii\base\Behavior;
use yii\base\Exception;
use yii\db\ActiveRecord;
use Yii;

/**
 * Created by PhpStorm.
 * User: johnny
 * Date: 17-8-1
 * Time: 下午3:15
 */
class UpdateBehavior extends Behavior
{
    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT=>function($event) {
                $record = $event->sender;
                if (!$record instanceof ActiveRecord) {
                    throw new Exception('invalid record');
                }
                if ($record->hasAttribute('uuid') && empty($record->uuid)) {
                    $record->uuid = time() . Yii::$app->security->generateRandomString(5);
                }

                if ($record->hasAttribute('created_time') && empty($record->created_time)) {
                    $record->created_time = time();
                }

                if ($record->hasAttribute('create_time') && empty($record->create_time)) {
                    $record->create_time = time();
                }

                if ($record->hasAttribute('updated_time') && empty($record->updated_time)) {
                    $record->updated_time = time();
                }

                if ($record->hasAttribute('update_time') && empty($record->update_time)) {
                    $record->update_time = time();
                }

                if ($record->hasAttribute('created_uuid') && empty($record->created_uuid)) {
                    $record->created_uuid = Yii::$app->getUser()->getId();
                }
            },
            ActiveRecord::EVENT_AFTER_UPDATE=>function($event) {
                $record = $event->sender;
                if (!$record instanceof ActiveRecord) {
                    throw new Exception('invalid record');
                }

                if ($record->hasAttribute('updated_time') && empty($record->updated_time)) {
                    $record->updated_time = time();
                }

                if ($record->hasAttribute('update_time') && empty($record->update_time)) {
                    $record->update_time = time();
                }
            }
        ];
    }
}